import axios from 'axios'
import qs from 'qs'

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'

const service = axios.create({
    baseURL: '/api', //process.env.BASE_API, // api 的 base_url
    timeout: 10000 // request timeout 请求超时时间
});

// request interceptor 请求拦截器
service.interceptors.request.use(
    config => {
        const flag = config.headers['Content-Type'] && config.headers['Content-Type'].indexOf('application/json') !== -1
        if (!flag) {
            const mult = config.headers['Content-Type'] && config.headers['Content-Type'].indexOf('multipart/form-data') !== -1
            if (mult) {
                this.config.data = config.data
            } else {
                config.data = qs.stringify(config.data)
            }
        } else {
            if (config.data === undefined || config.data === null) {
                config.data = {}  // 不传参的情况下 json类型的提交数据，校准为 空对象
            }
        }
        return config
    },
    error => {
        return Promise.reject(error)
    }
);

// response interceptor 响应拦截器
service.interceptors.response.use(
    response => {
        return response
    },
    error => {
        if (error.response && error.response.status === 404) {
            console.log("404错误")  //跳转到xx页面
        }
        return Promise.reject(error)
    });

export default service
